/*!
 * jQuery echo form Plugin v1.0
 *
 *https://github.com/Sayi/echoForm
 *
 * Copyright 2013 Sayi
 * Released under the MIT license
 */
(function($) {

	function echoForm(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.echoForm.defaults, options);
		this.init();
	}

	echoForm.prototype = {

		constructor : echoForm,

		init : function() {
			// validate
			if (!this.$element.is('form') ) {
				this.log("No Form selected, returning nothing.");
				return;
			}
			if (!this.options.data) {
				return;
			}
			//console.log(this.options.data);

			switch (this.options.datatype) {
			case 'text':
				this.echoText();
				break;
			case 'json':
				this.echoJson();
				break;
			case 'attribute':
				this.echoAttribute();
				break;
			case 'object':
				this.echoObject();
				break;
			default:
				this.log("cannot retieve the date type" + this.options.datatype
						+ ", returning nothing.");
				return;
			}
		},

		// {A=a, B=b}
		echoText : function() {

		},

		// {"A":"a","B":"b"}
		echoJson : function() {
		},

		// {A:'a',B:'b'}
		echoObject : function() {
			var that = this;
			$.each(this.options.data, function(name, value) {
				if (that.isEcho(name)) {
					that.$element.find('[name=' + name + ']').val(value);
				}
			});
		},

		// data-echo='A'
		echoAttribute : function() {

		},

		// is echo the form element,see ignoreAttr and ignoreClass
		isEcho : function(name) {
			var that = this, flag = true;
			var $echoElement = that.$element.find('[name=' + name + ']');
			// $.each(this.options.ignoreName, function(i, eleName){
			// if ($echoElement.is(eleName))
			// {flag = false;return false;}
			// });
			// if (!flag) return flag;
			$.each(this.options.ignoreAttr, function(attrName, attrValue) {
				if ($echoElement.attr(attrName) == attrValue) {
					flag = false;
					return false;
				}
			});
			// if (!flag) return flag;
			// $.each(this.options.ignoreClass, function(i, cls){
			// if ($echoElement.hasClass(cls))
			// {flag = false;return false;}
			// });
			return flag;
		},

		log : function(msg) {
			if (window.console) {
				console.warn(msg);
			}
		}
	}

	/*
	 * echo form PLUGIN DEFINITION ===========================
	 */

	$.fn.echoForm = function(options) {
		return this.each(function() {
			new echoForm(this, options);
		});
	}

	$.fn.echoForm.Constructor = echoForm

	$.fn.echoForm.defaults = {
		data : "",
		// json\attribute\object\text
		datatype : "object",
		ignoreAttr : {
			"type" : "password"
		}
	// ignoreName : [],
	// ignoreClass : ["hidden"]
	}

}(window.jQuery));